<script setup>
import dayjs from 'dayjs'
import { ref } from 'vue'

const showPicker = ref(false)
const currentPickerType = ref('text')

const currentDate = ref(dayjs().$d)
const minDate = dayjs().subtract(50, 'year').$d
const maxDate = dayjs().add(5, 'year').$d
const customFieldName = { text: 'name', children: 'children' }
const cascaderFieldNames = { text: 'name', value: 'adCode', children: 'children' }

const emits = defineEmits(['confirm'])
const props = defineProps({
  options: Array,
  defineAddress: String
})
const cascaderValue = ref(props.defineAddress)

/**
 * 确定
 * @param {*} e 
 */
const onConfirm = (e) => {
  emits('confirm', e)
  showPicker.value = false
}

/**
 * 打开选择器
 * @param {String} e
 */
const open = (e) => {
  // TODO: 默认值问题
  cascaderValue.value = null
  currentPickerType.value = e
  showPicker.value = true
}

defineExpose({
  open
})
</script>
<template>
  <van-popup v-model:show="showPicker" position="bottom">
    <template v-if="currentPickerType === 'text'"
      ><van-picker :columns="options" :columns-field-names="customFieldName" @confirm="onConfirm" @cancel="showPicker = false"
    /></template>
    <template v-else-if="currentPickerType === 'date'"
      ><van-datetime-picker
        v-model="currentDate"
        type="date"
        :min-date="minDate"
        :max-date="maxDate"
        title="选择年月日"
        @confirm="onConfirm"
        @cancel="showPicker = false"
    /></template>
    <template v-else-if="currentPickerType === 'cascader'">
      <van-cascader
        v-model="cascaderValue"
        title="请选择所在地区"
        :field-names="cascaderFieldNames"
        :options="options"
        @close="showPicker = false"
        @finish="onConfirm"
      />
    </template>
  </van-popup>
</template>
<style lang="less" scoped></style>
